import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'view-design'
class HttpRequest {
  // eslint-disable-next-line space-before-function-paren
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'my-admin-token': store.state.user.token
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url, bool) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        // console.log(res)
        this.destroy(url)
        // console.log(res.success)
        if (bool) {
          return res
        }
        if (!res.data.success) {
          if (res.data.errCode) {
            Message.error({
              content: res.data.errMsg,
              duration: 3
            })
          }
          if (res.data.errCode === '401' || res.data.errCode === 401) {
            store.dispatch('handleLogOut')
            router.push({
              name: 'login'
            })
          }
          return Promise.reject(res.data)
        }
        const { data, status } = res
        return {
          data: data.data,
          status
        }
      },
      error => {
        this.destroy(url)
        let errorInfo = error.response
        if (!errorInfo) {
          const {
            request: { statusText, status },
            config
          } = JSON.parse(JSON.stringify(error))
          errorInfo = {
            statusText,
            status,
            request: {
              responseURL: config.url
            }
          }
        }
        addErrorLog(errorInfo)
        return Promise.reject(error)
      }
    )
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
  requestExcelt (options) {
    const instance = axios.create()
    options = Object.assign({
      baseURL: this.baseUrl,
      headers: {
        'my-admin-token': store.state.user.token,
        'Content-Type': 'application/json;charset=UTF-8'
      },
      'responseType': 'blob'
    }, options)
    this.interceptors(instance, options.url, 'bool')
    return instance(options)
  }
}
export default HttpRequest
